package com.cloudbroker.bcs.platform.dav.middle.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.cloudbroker.bcs.common.util.IOUtil;
import com.cloudbroker.bcs.platform.dav.common.extservice.store.StoreService;
import com.cloudbroker.bcs.platform.dav.common.extservice.store.StoreServiceFactory;
import com.cloudbroker.bcs.platform.dav.middle.service.FileService;

/**
 * Created by xuyn15828 on 2016/4/11.
 */
@Service
public class FileServiceImpl implements FileService {
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Override
    public String transLocalFileUri(String userAvatar , boolean secret , Long customerId){
        int intSecret = secret ? 1 : 0;
        InputStream ips = null;
        try {
            URL url = new URL(userAvatar);
            ips = IOUtil.mark(url.openStream());
            StoreService storeService = StoreServiceFactory.getInstance().getStoreService();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = customerId + "_" + IOUtil.getFileType(IOUtil.reset(ips)) + "_" + intSecret + "_" + System.currentTimeMillis() + "_" + uuid.substring(0, 6);
            try {
                storeService.uploadFile(filename, IOUtil.reset(ips));
            } catch (Exception e) {
                logger.error("file upload error");
            }
            return filename;
        } catch (IOException e) {
            logger.error("trans local file uri error");
        } finally {
            IOUtil.close(ips);
        }
        return null;
    }
}
